<?php

namespace app\api\controller\worker;

use app\api\controller\Base;
use app\common\model\AdminModel;
use app\common\model\node\NodeModel;
use app\common\model\worker\CustomerAuthModel;
use app\common\model\worker\CustomerModel;
use app\common\model\worker\TaskModel;
use think\facade\Db;
use think\Request;

class TaskController extends Base
{
    private $model;

    /**
     * 构造方法
     * @access public
     * @throws \Exception
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->model = new TaskModel();
    }

    /**
     * 任务流列表
     */
    public function index(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $nodeType     = $this->request->param('node_type');
        $taskType     = $this->request->param('task_type',0);
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $searchData    = $this->getSearchData();
        //print_r($searchData);
        $query = [];
        if($nodeType==0){
            switch ($taskType){
                case 0:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                break;
                case 1:
                    $query[] = ['audit_admin_id','=',$this->loginInfo['id']];
                    break;
                case 2:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    break;
            }
        }
        $data          = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->where($query)->where('action_table_id',null)->count();
        $data['sql'] = $this->model->getLastSql();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)
                ->where($query)
                ->where('action_table_id',null)
                ->page($pageNumber, $pageSize)
                ->order($order)
                ->select()
                ->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
            $data['order'] = $order;
        }
        $this->result($data,'操作成功',1);
    }

    /**
     * 接受或拒绝任务
     */
    public function receiveTask(){
        $id  =$this->request->param('id');
        $status  =$this->request->param('status');
        //todo 验证登录人权限
        $this->model->where('id',$id)->update(['is_receive'=>$status,'receive_time'=>date('Y-m-d H:i:s')]);
        $this->success('操作成功');
    }

    /**
     * 获取任务步骤详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getProcess(){
        $id  =$this->request->param('id');
        $processInfo = $this->model->getProcessInfo($id);


        $this->result($processInfo,'操作成功',1);
    }


    /**
     * 添加任务
     */
    public function addTask(){
        $data = $this->request->param();
        $this->validate($data,[
            'customer_id|客户id'=>'require',
            'order_id|订单id'=>'require',
            'node_id|任务节点'=>'require',
            'process_id|任务内容'=>'require',
        ]);
        $nodeInfo = NodeModel::where('id',$data['node_id'])->find();
        if(empty($nodeInfo)) //exception('任务配置已被修改');
        {
            $this->result([],'任务配置已被修改',0);

        }


        if($nodeInfo['node_type']==0){
            if(empty($data['receive_admin_id'])) //exception('请指定任务执行人');
            {
                $this->result([],'请指定任务执行人',0);
            }



            $receiveAdminId = $data['receive_admin_id'];
        }
        if($nodeInfo['node_type']==1){
            $authInfo = CustomerAuthModel::where('customer_id',$data['customer_id'])->where('node_id',$data['node_id'])->find();
            if(empty($authInfo)) //exception('当前任务尚未指定执行人');
            {
                $this->result([],'当前任务尚未指定执行人',0);
            }



            $receiveAdminId = $authInfo['admin_id'];
        }
        if($nodeInfo['node_type']==2){
            $authInfo = CustomerAuthModel::where('order_id',$data['order_id'])->where('node_id',$data['node_id'])->find();
            if(empty($authInfo)){ //exception('当前任务尚未指定执行人');
                $this->result([],'当前任务尚未指定执行人',0);
            }



            $receiveAdminId = $authInfo['admin_id'];
        }
        //todo 验证登录人执行权限
        $info = $this->model->addTask($data['customer_id'],0,$data['node_id'],$data['process_id'],$this->loginInfo['id'],$receiveAdminId);


        $this->result($info,'操作成功',1);

    }

    /**
     *自由任务发布
     */
    public function customTask(){
        $data = $this->request->param();
        $this->validate($data,[
            'receive_admin_ids|执行人'=>'require',
            'audit_admin_ids|审核人'=>'require',
            'node_name|任务内容'=>'require',
            'deadline_time|截止日期'=>'require',
        ]);
        if(!empty($data['task_imgs'])){
            $data['task_imgs'] = json_encode($data['task_imgs'],JSON_UNESCAPED_UNICODE);
        }
        if(!empty($data['task_file'])){
            $data['task_file'] = json_encode($data['task_file'],JSON_UNESCAPED_UNICODE);
        }
        $this->model->addCustomTask($data,$this->loginInfo['id']);
        //todo 发送订阅消息
        $receiveList = AdminModel::where('id','in',$data['receive_admin_ids'])->where('openid','<>','')->select()->toArray();
        $result = [];
        if(!empty($receiveList)){
            foreach ($receiveList as $k=>$v){
                $message = [
                    'openid' =>$v['openid'],     // 接收者（用户）的 openid
                    'page' => '/pages/task/index',
                    'msg' => [
                        'thing9' => [
                            'value' => '收到新任务',
                        ],
                        'time3' => [
                            'value' => date('Y-m-d H:i'),
                        ],
                        'time7' => [
                            'value' => date('Y-m-d H:i'),
                        ],
                        'time8' => [
                            'value' => $data['deadline_time'],
                        ],
                        'thing4' => [
                            'value' => $data['node_name'],
                        ],
                    ],
                ];
                $res = sendMiniMessage($message);
                $result[] = ['id'=>$v['id'],'mobile'=>$v['mobile'],'nickname'=>$v['nickname'],'errcode'=>$res['errcode']];
            }
        }
        $this->result($result,'ok',1);
    }

    /**
     * 获取任务详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo(){
        $id = $this->request->param('task_id');
        $info = $this->model->getInfo($id);
        $this->result($info,'操作成功',1);
    }

    /**
     * 提交任务
     */
    public function submitTask(){
        $data = $this->request->param();
        $info = $this->model->submitTask($data,$this->loginInfo['id']);
        $this->result($info,'操作成功',1);
    }

    public function submitCustomTask(){
        $data = $this->request->param();
        $this->validate($data,[
            'id|任务id'=>'require',
            'content|执行内容'=>'require',
        ]);
        $content = [
            ['field_label'=>'执行情况','input_type'=>'_textarea','is_required'=>1,'content'=>$data['content']],
            ['field_label'=>'图片','input_type'=>'_uploadImages','is_required'=>0,'content'=>empty($data['imgs'])?'':$data['imgs']],
            ['field_label'=>'附件','input_type'=>'_uploadFiles','is_required'=>0,'content'=>empty($data['file'])?'':$data['file']],
        ];
        $this->model->where('id',$data['id'])->update([
            'process_content'=>json_encode($content,JSON_UNESCAPED_UNICODE),
            'is_submit'=>1,
            'submit_time'=>date('Y-m-d H:i:s'),
        ]);
        $info = $this->model->where('id',$data['id'])->find();
        //todo 发送订阅消息
        $result = [];
        $sendAdmin = AdminModel::where('id',$info['admin_id'])->find();
        if(!empty($sendAdmin['openid'])){
            $message = [
                'openid' =>$sendAdmin['openid'],     // 接收者（用户）的 openid
                'page' => '/pages/task/custom_task_info?task_id='.$info['id'],
                'msg' => [
                    'thing9' => [
                        'value' => '任务提交反馈',
                    ],
                    'time3' => [
                        'value' => date('Y-m-d H:i'),
                    ],
                    'time7' => [
                        'value' => $info['receive_time'],
                    ],
                    'time8' => [
                        'value' => date('Y-m-d H:i'),
                    ],
                    'thing4' => [
                        'value' => $data['content'],
                    ],
                ],
            ];
            $res = sendMiniMessage($message);
            $result[] = ['id'=>$sendAdmin['id'],'mobile'=>$sendAdmin['mobile'],'nickname'=>$sendAdmin['nickname'],'errcode'=>$res['errcode']];
        }
        //todo 如果需要审核，提交给审核人
        $auditAdmins = [];
        if(!empty($info['audit_admin_ids'])){
            $auditAdmins = explode(',',$info['audit_admin_ids']);
            $auditAdmins = array_diff($auditAdmins,[$info['admin_id']]);
        }
        if(!empty($auditAdmins)){
            $auditList = AdminModel::where('id','in',$auditAdmins)->where('openid','<>','')->select()->toArray();
            if(!empty($auditList)){
               foreach ($auditList as $k=>$v){
                   $message = [
                       'openid' =>$v['openid'],     // 接收者（用户）的 openid
                       'page' => '/pages/task/custom_task_info?task_id='.$info['id'],
                       'msg' => [
                           'thing9' => [
                               'value' => '收到审核任务',
                           ],
                           'time3' => [
                               'value' => date('Y-m-d H:i'),
                           ],
                           'time7' => [
                               'value' => $info['receive_time'],
                           ],
                           'time8' => [
                               'value' => date('Y-m-d H:i'),
                           ],
                           'thing4' => [
                               'value' => $data['content'],
                           ],
                       ],
                   ];
                   $res = sendMiniMessage($message);
                   $result[] = ['id'=>$v['id'],'mobile'=>$v['mobile'],'nickname'=>$v['nickname'],'errcode'=>$res['errcode']];
               }
            }
        }

        $this->result($result,'操作成功',1);
    }

    /**
     * 重启任务
     */
    public function revokeTask(){
        $id = $this->request->param('id');
        $this->model->revokeTask($id,$this->loginInfo['id']);
        $this->result([],'操作成功',1);
    }
    /**
     * 审核任务
     */
    public function auditTask(){
        $data = $this->request->param();
        if($data['audit_status']==1){
            $info = $this->model->auditTask($data['id'],$this->loginInfo['id'],$data);
        }else{
            $data['process_id'] = $data['process_id'] ?? '';
            $task_imgs  = $data['task_imgs'] ?? '';
            if($task_imgs){
                $task_imgs          = json_encode($data['task_imgs'],JSON_UNESCAPED_UNICODE);
            }

            $info = $this->model->rejectTask($data['id'],$data['process_id'],$data['audit_idea'],$this->loginInfo['id'],$task_imgs);
        }
        $this->model->sendAuditTask($data);
        $this->result($info,'操作成功',1);

    }

    /**
     * 审核自定义任务
     */
    public function auditCustomTask(){
        $data = $this->request->param();
        $this->model->where('id',$data['id'])->update([
            'audit_status'=>$data['audit_status'],
            'audit_admin_id'=>$this->loginInfo['id'],
            'audit_idea'=>$data['audit_idea'],
            'audit_time'=>date('Y-m-d H:i:s'),
        ]);
        $info = $this->model->where('id',$data['id'])->find();
        //todo 给任务执行人和任务发起人发送消息
        $auditMsg = $data['audit_status']==1?'任务已审核':'任务已驳回';
        $result = [];
        $sendAdmin = AdminModel::where('id',$info['admin_id'])->find();
        $message = [
            'page' => '/pages/task/custom_task_info?task_id='.$info['id'],
            'msg' => [
                'thing9' => [
                    'value' => $auditMsg,
                ],
                'time3' => [
                    'value' => date('Y-m-d H:i'),
                ],
                'time7' => [
                    'value' => $info['audit_time'],
                ],
                'time8' => [
                    'value' => date('Y-m-d H:i'),
                ],
                'thing4' => [
                    'value' => $info['node_name'],
                ],
            ],
        ];
        if(!empty($sendAdmin['openid'])){
            $message['openid'] = $sendAdmin['openid'];
            $res = sendMiniMessage($message);
            $result[] = ['id'=>$sendAdmin['id'],'mobile'=>$sendAdmin['mobile'],'nickname'=>$sendAdmin['nickname'],'errcode'=>$res['errcode']];
        }
        $receiveAdmin = AdminModel::where('id',$info['receive_admin_id'])->find();
        if(!empty($receiveAdmin['openid'])){
            $message['openid'] = $receiveAdmin['openid'];
            $res = sendMiniMessage($message);
            $result[] = ['id'=>$receiveAdmin['id'],'mobile'=>$receiveAdmin['mobile'],'nickname'=>$receiveAdmin['nickname'],'errcode'=>$res['errcode']];
        }
        $this->result($info,'操作成功',1);
    }
    /**
    * 取消任务
    */
    public function cancelTask(){
        $id = $this->request->param('id');
        //todo 验证登录人执行权限
        $this->model->del($id);
        $this->result([],'操作成功',1);
    }

    /**
     * 我的任务列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myTask(){
        $pageSize      = $this->request->param('pageSize/d', 20); //每页多少条
        $pageNumber    = $this->request->param('pageNumber/d'); //当前页
        $sortName      = $this->request->param('sortName','update_time'); //排序字段
        $sortOrder     = $this->request->param('sortOrder', 'desc'); //升序降序
        $order         = !empty($sortName) ? "{$sortName} {$sortOrder}" : ''; //排序
        $searchData    = $this->getSearchData();
        $query = [];
        $taskType = $this->request->param('task_type',0);//0我的任务 1我的审核 2我发出的
        $status = $this->request->param('status',0);
        if($taskType==0){
            //0待接受 1进行中 2待审核 3已完成
            switch ($status){
                case 0:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',0];
                    break;
                case 1:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','=',0];
                    $query[] = ['is_receive','=',1];
                    $query[] = ['is_submit','=',0];
                    break;
                case 2:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','=',0];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',0];
                    $query[] = ['is_submit','=',1];
                    break;
                case 3:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
                    break;
            }
        }
        if($taskType==1){
            switch ($status){
                //0待审核 1已审核 2已驳回
                case 0:
                    $query[] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},audit_admin_ids)")];
                    $query[] = ['process_status','=',0];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',0];
                    $query[] = ['is_submit','=',1];
                    break;
                case 1:
                    //$query[] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},audit_admin_ids)")];
                    $query[] = ['audit_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',1];
                    $query[] = ['is_submit','=',1];
                    break;
                case 2:
                    $query[] = ['audit_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',-1];
                    $query[] = ['is_submit','=',1];
                    break;
            }
        }
        if($taskType==2){
            switch ($status){
                //0待接受 1进行中 2待审核 3已完成
                case 0:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',0];
                    break;
                case 1:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','=',0];
                    $query[] = ['is_receive','=',1];
                    $query[] = ['is_submit','=',0];
                    break;
                case 2:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','=',0];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',0];
                    $query[] = ['is_submit','=',1];
                    break;
                case 3:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
                    //$query[] = ['process_status','>',0];
                    break;
            }
        }
        if($taskType==3) {
            switch ($status) {
                //0待接受 1进行中 2待审核 3已完成
                case 0:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['is_receive', '=', 0];
                    break;
                case 1:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['process_status', '=', 0];
                    $query[] = ['is_receive', '=', 1];
                    $query[] = ['is_submit', '=', 0];
                    break;
                case 2:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['process_status', '=', 0];
                    $query[] = ['is_audit', '=', 1];
                    $query[] = ['audit_status', '=', 0];
                    $query[] = ['is_submit', '=', 1];
                    break;
                case 3:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['', 'exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
                    //$query[] = ['process_status','>',0];
                    break;
            }
        }
        $data          = ['total' => 0, 'rows' => []];
        $data['total'] = $this->model->withSearch('filter', $searchData)->where($query)->count();
        $data['sql'] = $this->model->getLastSql();
        if ($data['total'] > 0) {
            $rows = $this->model->withSearch('filter', $searchData)
                ->where($query)
                ->where('action_table_id',null)
                ->page($pageNumber, $pageSize)
                ->order($order)
                ->select()
                ->toArray();
            $rows = $this->model->_formatList($rows);
            $data['rows'] = $rows;
        }

        $this->result($data,'操作成功',1);
    }

    /**
     * 我的待办
     * 0待接受 1执行中 2待我审核 3发出待接受
     */
    public function todoList(){
        $query = [];
        $query[0][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[0][] = ['is_receive','=',0];
        $query[1][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[1][] = ['is_receive','=',1];
        $query[1][] = ['is_submit','=',0];
        $query[2][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},audit_admin_ids)")];
        //$query[2][] = ['audit_admin_id','=',$this->loginInfo['id']];
        $query[2][] = ['is_audit','=',1];
        $query[2][] = ['audit_status','=',0];
        $query[2][] = ['is_submit','=',0];
        $query[3][] = ['admin_id','=',$this->loginInfo['id']];
        $query[3][] = ['is_receive','=',0];
        $list0= $this->model->where($query[0])->where('action_table_id',null)->order('create_time asc')->select()->toArray();
        $list1= $this->model->where($query[1])->where('action_table_id',null)->order('receive_time asc')->select()->toArray();
        $list2= $this->model->where($query[2])->where('action_table_id',null)->order('submit_time asc')->select()->toArray();
        $list3= $this->model->where($query[3])->where('action_table_id',null)->order('create_time asc')->select()->toArray();

        $list0 = $this->model->_formatList($list0);
        $data[] = ['name'=>'待接受','list'=>$list0,'count'=>count($list0)];

        $list1 = $this->model->_formatList($list1);
        $data[] = ['name'=>'执行中','list'=>$list1,'count'=>count($list1)];

        $list2 = $this->model->_formatList($list2);
        $data[] = ['name'=>'待我审核','list'=>$list2,'count'=>count($list2)];


        $list3 = $this->model->_formatList($list3);
        $data[] = ['name'=>'我发出的','list'=>$list3,'count'=>count($list3)];

        $this->result($data,'操作成功',1);
    }

    /**
     * todo 数字
     *  1待接受 2执行中 3待审核  4待我审核 5发出待接受 6我发出执行中 7抄送给我待执行 8抄送给我执行中 9抄送给我审核中的
     */
    public function taskNum(){
        $query = [];
        $query[1][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[1][] = ['is_receive','=',0];

        $query[2][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[2][] = ['is_receive','=',1];
        $query[2][] = ['is_submit','=',0];

        $query[3][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[3][] = ['is_audit','=',1];
        $query[3][] = ['audit_status','=',0];
        $query[3][] = ['process_status','=',0];
        $query[3][] = ['is_submit','=',1];

        $query[4][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},audit_admin_ids)")];
        //$query[4][] = ['audit_admin_id','=',$this->loginInfo['id']];
        $query[4][] = ['is_audit','=',1];
        $query[4][] = ['audit_status','=',0];
        $query[4][] = ['process_status','=',0];
        $query[4][] = ['is_submit','=',1];

        $query[5][] = ['admin_id','=',$this->loginInfo['id']];
        $query[5][] = ['is_receive','=',0];

        $query[6][] = ['admin_id','=',$this->loginInfo['id']];
        $query[6][] = ['is_receive','=',1];
        $query[6][] = ['is_submit','=',0];

        $query[7][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[7][] = ['is_receive','=',0];

        $query[8][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[8][] = ['is_receive','=',1];
        $query[8][] = ['is_submit','=',0];

        $query[9][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[9][] = ['is_audit','=',1];
        $query[9][] = ['audit_status','=',0];
        $query[9][] = ['process_status','=',0];
        $query[9][] = ['is_submit','=',1];

        $data['total_01']= $this->model->where($query[1])->where('action_table_id',null)->count();
        $data['total_02']= $this->model->where($query[2])->where('action_table_id',null)->count();
        $data['total_03']= $this->model->where($query[3])->where('action_table_id',null)->count();
        $data['total_04']= $this->model->where($query[4])->where('action_table_id',null)->count();
        $data['total_05']= $this->model->where($query[5])->where('action_table_id',null)->count();
        $data['total_06']= $this->model->where($query[6])->where('action_table_id',null)->count();
        $data['total_07']= $this->model->where($query[7])->where('action_table_id',null)->count();
        $data['total_08']= $this->model->where($query[8])->where('action_table_id',null)->count();
        $data['total_09']= $this->model->where($query[9])->where('action_table_id',null)->count();
        $this->result($data,'操作成功',1);
    }

    /**
     * 我的任务列表
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myTaskList(){
        $pageSize      = $this->request->param('pageSize/d', 20); //当前页
        $pageNumber    = $this->request->param('pageNumber/d',1); //每页多少条

        $query = [];
        $taskType = $this->request->param('type',0);// 0我发出的 //1我审核得 2抄送给我
        $status = $this->request->param('status',0);//0待接受 1审批中 2审批通过 3被驳回
        //我发出的
        if($taskType==0){
            //0待接受 1审核中 2审核通过 3审核驳回

            switch ($status){
                //0待接受 1审批中 2审批通过 3被驳回
                case 0:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',0];
                    break;
                case 1:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',1];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',0];
                    break;
                case 2:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];

                    break;
                case 3:
                    $query[] = ['admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','<>',0];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',-1];
                    //$query[] = ['process_status','>',0];
                    break;
            }

        }
        //我审核的
        if($taskType==1){
            switch ($status){
                case 0:

                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',0];
                    break;
                case 1:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['is_receive','=',1];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',0];

                    break;
                case 2:
                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];

                    break;
                case 3:


                    $query[] = ['receive_admin_id','=',$this->loginInfo['id']];
                    $query[] = ['process_status','<>',0];
                    $query[] = ['is_audit','=',1];
                    $query[] = ['audit_status','=',-1];
                    break;
            }
        }

        if($taskType==2) {
            switch ($status) {
                //0待接受 1进行中 2被驳回 3已完成
                case 0:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['is_receive', '=', 0];
                    break;
                case 1:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    //$query[] = ['process_status', '=', 0];
                    $query[] = ['is_receive', '=', 1];
                    $query[] = ['is_audit', '=', 1];
                    $query[] = ['audit_status', '=', 0];
                    break;
                case 2:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['', 'exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
                    break;
                case 3:
                    $query[] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
                    $query[] = ['process_status', '<>', 0];
                    $query[] = ['is_receive', '=', 1];
                    $query[] = ['is_audit', '=', 1];
                    $query[] = ['audit_status', '=', -1];
                    //$query[] = ['process_status','>',0];
                    break;
            }
        }

       // var_dump($query);exit;
            $list = $this->model
                ->where($query)->with(['adminInfoData','customerInfoData'])
                ->where('action_table_id','<>',null)
                ->order('create_time','desc')
                ->paginate($pageSize, false, ['page' =>$pageNumber ]);



        $this->result($list,'操作成功',1);
    }
    /**
     *
     * todo 数字 0待接受 1审批中 2审批通过 3被驳回
     *
     */
    public function taskNumShow(){
        $query = [];

        //我发出待接受
        $query[1][] = ['admin_id','=',$this->loginInfo['id']];
        $query[1][] = ['is_receive','=',0];

        //我发出执行中
        $query[2][] = ['admin_id','=',$this->loginInfo['id']];
        $query[2][] = ['is_receive','=',1];
        $query[2][] = ['is_audit','=',1];
        $query[2][] = ['audit_status','=',0];
        $query[2][] = ['process_status','=',0];
        //审核通过
        $query[3][] = ['admin_id','=',$this->loginInfo['id']];
        $query[3][] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
        //我发出被驳回
        $query[4][] = ['admin_id','=',$this->loginInfo['id']];
        $query[4][] = ['is_receive','=',1];
        $query[4][] = ['is_audit','=',1];
        $query[4][] = ['audit_status','=',-1];
        $query[4][] = ['process_status','<>',0];

        //待接受
        $query[5][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[5][] = ['is_receive','=',0];

        //审批中
        $query[6][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[6][] = ['is_audit','=',1];
        $query[6][] = ['audit_status','=',0];
        $query[6][] = ['process_status','=',0];
        $query[6][] = ['is_receive','=',1];
        //审核通过
        //审核通过
        $query[7][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[7][] = ['','exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
        //被驳回
        $query[8][] = ['receive_admin_id','=',$this->loginInfo['id']];
        $query[8][] = ['is_audit','=',1];
        $query[8][] = ['audit_status','=',-1];
        $query[8][] = ['process_status','<>',0];





        //抄送给我待接受
        $query[9][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[9][] = ['is_receive','=',0];

            //抄送给我执行中
        $query[10][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[10][] = ['is_receive','=',1];
        $query[10][] = ['is_audit','=',1];
        $query[10][] = ['audit_status','=',0];
        $query[10][] = ['process_status','=',0];
        //抄送给我审核通过的
        $query[11][] = ['', 'exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[11][] = ['', 'exp', Db::raw("(node_type<99 and process_status>0) or (node_type=99 and audit_status<>0)")];
        //抄送给我被驳回
        $query[12][] = ['','exp', Db::raw("find_in_set({$this->loginInfo['id']},copy_admin_ids)")];
        $query[12][] = ['is_receive','=',1];
        $query[12][] = ['is_audit','=',1];
        $query[12][] = ['audit_status','=',-1];
        $query[12][] = ['process_status','<>',0];

        $data['total_01']= $this->model->where('action_table_id','<>',null)->where($query[1])->count();
        $data['total_02']= $this->model->where('action_table_id','<>',null)->where($query[2])->count();
        $data['total_03']= $this->model->where('action_table_id','<>',null)->where($query[3])->count();
        $data['total_04']= $this->model->where('action_table_id','<>',null)->where($query[4])->count();

        $data['total_05']= $this->model->where('action_table_id','<>',null)->where($query[5])->count();
        $data['total_06']= $this->model->where('action_table_id','<>',null)->where($query[6])->count();
        $data['total_07']= $this->model->where('action_table_id','<>',null)->where($query[7])->count();
        $data['total_08']= $this->model->where('action_table_id','<>',null)->where($query[8])->count();

        $data['total_09']= $this->model->where('action_table_id','<>',null)->where($query[9])->count();
        $data['total_10']= $this->model->where('action_table_id','<>',null)->where($query[10])->count();
        $data['total_11']= $this->model->where('action_table_id','<>',null)->where($query[11])->count();
        $data['total_12']= $this->model->where('action_table_id','<>',null)->where($query[12])->count();
        $this->result($data,'操作成功',1);
    }
    //任务详情
    public function getTaskInfo(Request $request){

        $id = $request->param('id', '');

        $data = [];
        $taskInfo = TaskModel::where('id', $id)->find();
        $data['customerInfo'] = CustomerModel::alias('ct')
            ->leftjoin('customer_channel cc','ct.channel_id = cc.id')
            ->leftjoin('recommend r','r.id = ct.recommend_id')
            ->where('ct.id',$taskInfo['customer_id'])
            ->field('ct.business_name,ct.name,ct.mobile,ct.province,ct.city,
            ct.dist,ct.house_estate,ct.address,cc.name as channel_name,r.recommend_name,customer_pain_content,
            order_total_amount,payment_amount
            ')
            ->find();
        if($taskInfo['node_id'] == 6){
            //预算
            $data['budgetInfo']  = TaskModel::alias('t')->leftjoin('customer_budget cb','cb.id = t.action_table_id')
                ->leftJoin('admin a', 'a.id = cb.admin_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.goods_name,cb.budget_amount,cb.finish_time,a.nickname as admin_name,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 7){
            //量房
            $data['rulerInfo']  = TaskModel::alias('t')->leftjoin('customer_ruler cb','cb.id = t.action_table_id')
                ->leftJoin('admin a', 'a.id = cb.admin_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.goods_name,cb.budget_amount,cb.finish_time,a.nickname as admin_name,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 8){
            //图纸审核
            $data['drawInfo']  = TaskModel::alias('t')->leftjoin('customer_draw cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.goods_name,cb.drawing_imgs,cb.drawing_remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif ($taskInfo['node_id'] == 9){
            //签合同
            $data['goodsContractInfo']  = TaskModel::alias('t')->leftjoin('customer_contract cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.goods_name,cb.expect_time,cb.retail_price,cb.discount_price,cb.final_price,cb.contract_imgs,cb.price_detail_imgs,
                cb.drawing_imgs,cb.sample_imgs,cb.notice_imgs,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }
        elseif ($taskInfo['node_id'] == 10){
            //放弃品类
            $data['goodsDesertInfo']  = TaskModel::alias('t')->leftjoin('customer_goods_desert cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.goods_name,cb.customer_brand,cb.desert_status,cb.retail_price,cb.discount_price,cb.final_price,cb.budget_price,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 11){
            //收款
            $data['putPaymentInfo']  = TaskModel::alias('t')->leftjoin('customer_payment cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.create_time,cb.pay_type,cb.pay_amount,cb.receipt_imgs,cb.voucher_imgs,cb.pay_remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 12){
            //退款
            $data['quitPaymentInfo']  = TaskModel::alias('t')->leftjoin('customer_payment cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.create_time,cb.pay_amount,cb.account_name,cb.account_number,cb.bank_name,cb.open_bank,cb.pay_remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 13){
            //放弃客户
            $data['customerDesertInfo']  = TaskModel::alias('t')->leftjoin('customer_desert cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.customer_brand,cb.desert_status,cb.retail_price,cb.discount_price,cb.final_price,cb.budget_price,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 14){
            //申请售后
            $data['saleAfterInfo']  = TaskModel::alias('t')->leftjoin('sale_after cb','cb.id = t.action_table_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->where('t.action_table_id', $taskInfo['action_table_id'])
                ->field('cb.sale_name,cb.sale_moblie,cb.sale_time,cb.is_make,cb.make_time,cb.is_pay,cb.amount,cb.sale_imgs,a.nickname as sale_admin_name,
                cb.is_pay_wage,cb.wage_amount,cb.pay_remark,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 15){
            //完成售后
            $data['saleAfterDetailInfo']  = TaskModel::alias('t')->leftjoin('sale_after_detail cb','cb.id = t.action_table_id')


                ->leftJoin('sale_after sa', 'sa.id = cb.sale_id')
                ->leftJoin('admin a', 'a.id = sa.sale_admin_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('sa.sale_name,sa.sale_moblie,sa.sale_time,sa.make_time,sa.sale_imgs,cb.result_imgs,a.nickname as sale_admin_name,sa.wage_amount,sa.amount,cb.voucher_imgs,cb.remark,t.audit_idea')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 16){
            //待下单
            $data['daiOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->leftJoin('customer_contract cc', 'cc.id = cgd.contract_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.install_notices,cc.*,t.process_name,cb.back_files')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 17){
            //订单复核
            $data['fuheOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->leftJoin('customer_contract cc', 'cc.id = cgd.contract_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.back_files,t.audit_idea,t.process_name,cc.*')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 18){
            //财务核算
            $data['hesuanOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->leftJoin('customer_contract cc', 'cc.id = cgd.contract_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.back_files,cb.cost_files,cb.wage_infos,cb.rebate_infos,cb.gross_profit,cb.is_diff,cb.diff_content,t.audit_idea,t.process_name,cc.*')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 19){
            //补材料
            $data['cailiaoOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.back_files,cb.cost_files,cb.total_amount,cb.install_notices,cb.wage_infos,cb.rebate_infos,cb.gross_profit,cb.is_diff,cb.diff_content,t.audit_idea,t.process_name,cgd.type,cgd.rectify_content,cgd.goods_name')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 20){
            //美容
            $data['meirongOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.back_files,cb.cost_files,cb.total_amount,cb.install_notices,cb.wage_infos,cb.rebate_infos,cb.gross_profit,cb.is_diff,cb.diff_content,t.audit_idea,t.process_name,cgd.rectify_content,cgd.goods_name')
                ->find()
                ->toArray();
        }elseif($taskInfo['node_id'] == 21){
            //安装
            $data['anzhuangOrderInfo']  = TaskModel::alias('t')->leftjoin('order cb','cb.id = t.action_table_id')
                ->leftJoin('customer_goods_data cgd', 'cgd.id = cb.goods_data_id')
                ->where('cb.id', $taskInfo['action_table_id'])
                ->field('cb.cad_imgs,cb.back_files,cb.cost_files,cb.total_amount,cb.install_notices,cb.wage_infos,cb.rebate_infos,cb.gross_profit,cb.is_diff,cb.diff_content,t.audit_idea,t.process_name,cgd.rectify_content,cgd.goods_name')
                ->find()
                ->toArray();
        }



        $this->result($data,'操作成功',1);
    }
    //删除
    public function myTaskDel($id){
        $info =  $this->model->where('id',$id)->find();
        if($info['is_receive']>0) exception('任务已接受，无法取消');
        if($info['process_status']>0) exception('任务已执行，无法取消');
        $data = $this->model->where('id',$id)->delete();

        $this->result($data,'操作成功',1);
    }



}
